package com.uenpay.im.ui.old.activity.personal;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.listener.OnHttpRequestTextListener;
import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.net.HttpTextAsyncTask;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.area.AreaActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.TakePhotoActivity;
import com.uenpay.im.callback.IDateDailogListener;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.OnCommonCallBack;
import com.uenpay.im.callback.OnUploadFile2Listener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.entities.PersonInfoConstant;
import com.uenpay.im.entities.QYXUserEntity;
import com.uenpay.im.invokeitems.UploadFile;
import com.uenpay.im.invokeitems.person.GetPersonInfoInvokeItem;
import com.uenpay.im.invokeitems.person.UpdateInfoInvokItem;
import com.uenpay.im.view.PictureShowActivity;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.MyDateDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

/**
 * 我的详情页面
 *
 * @author SL
 * @CopyRight http://www.qiyunxin.com
 *
 */
public class MeDetailActivity extends BaseActivity {

	private final int CHOOSE_TAKE_PHOTO_REQUEST_CODE = 110;
	private final int CHOOSE_IMAGE_REQUEST_CODE = 111;
	private final int CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE = 112;
	private int sex_type = 0;
	private View loading;
	private RoundImageView me_detail_my_avatar;
	private TextView me_detail_my_name, me_detail_my_sex, me_detail_my_app_num,
			me_detail_my_email, me_detail_age_tv, me_detail_brithday_tv,
			me_detail_my_area, me_detail_my_signature;
	private boolean is_from_talk = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isFullScreen=true;
		super.onCreate(savedInstanceState);
	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_me_detail_layout;
	}

	@Override
	public void initView(View view) {
		if (getIntent() != null) {
			is_from_talk = getIntent().getBooleanExtra("is_from_talk", false);
		}
		initView();
		initListener();
		getPersonInfo();
	}

	protected void initView() {
		((TextView) findViewById(R.id.title_textview)).setText(getResources()
				.getString(R.string.me_detail));
		loading = findViewById(R.id.loading);
		me_detail_my_avatar = (RoundImageView) findViewById(R.id.me_detail_my_avatar);
		me_detail_my_name = (TextView) findViewById(R.id.me_detail_my_name);
		me_detail_my_sex = (TextView) findViewById(R.id.me_detail_my_sex);
		me_detail_my_email = (TextView) findViewById(R.id.me_detail_my_email);
		me_detail_my_app_num = (TextView) findViewById(R.id.me_detail_my_app_num);
		me_detail_age_tv = (TextView) findViewById(R.id.me_detail_age_tv);
		me_detail_brithday_tv = (TextView) findViewById(R.id.me_detail_brithday_tv);
		me_detail_my_area = (TextView) findViewById(R.id.me_detail_my_area);
		me_detail_my_signature = (TextView) findViewById(R.id.me_detail_my_signature);
	}

	protected void initListener() {
		findViewById(R.id.me_detail_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						updateAvatarDialog();
					}
				});
		findViewById(R.id.me_detail_my_area_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(MeDetailActivity.this,
								AreaActivity.class);
						startActivityForResult(intent,
								PersonInfoConstant.updateArea);
					}
				});
		findViewById(R.id.me_detail_my_qrcode_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						ActivityHandle.startActivity(MeDetailActivity.this,
								QRCodeActivity.class, null, -1);
					}
				});
		me_detail_my_avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String bigpath = "";
				if (!TextUtils.isEmpty(APIConfiguration.getAvatarUrlBig(
						IMApplication.getCustId(), PacketType.PERSONAL))) {
					bigpath = APIConfiguration.getAvatarUrlBig(
							IMApplication.getCustId(), PacketType.PERSONAL);
				} else {
					return;
				}
				ArrayList<String> imgs = new ArrayList<String>();
				Intent show = new Intent(MeDetailActivity.this,
						PictureShowActivity.class);
				show.putExtra("content", bigpath);
				imgs.add(bigpath);
				show.putStringArrayListExtra("imgList", imgs);
				startActivity(show);

			}
		});
		//返回键点击
		findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

	}

	public void onActionMeDetail(View v) {
		final int id = v.getId();
		if (id == R.id.age_layout) {
			if (is_from_talk) {
				return;
			}
			Intent ageIntent = new Intent(MeDetailActivity.this,
					EditInfoActivity.class);
			ageIntent.putExtra("oldStr", me_detail_age_tv.getText().toString());
			ageIntent.putExtra("update_type", PersonInfoConstant.updateAge);
			startActivityForResult(ageIntent, PersonInfoConstant.updateAge);

		} else if (id == R.id.me_detail_my_name_layout) {
			if (is_from_talk) {
				return;
			}
			Intent intent = new Intent(MeDetailActivity.this,
					EditInfoActivity.class);
			intent.putExtra("oldStr", me_detail_my_name.getText().toString());
			intent.putExtra("update_type", PersonInfoConstant.updateName);
			startActivityForResult(intent, PersonInfoConstant.updateName);

		} else if (id == R.id.me_detail_my_sex_layout) {
			if (is_from_talk) {
				return;
			}
			Intent intent11 = new Intent(MeDetailActivity.this,
					UpdateSexActivity.class);
			intent11.putExtra("sex_type", sex_type);
			startActivityForResult(intent11, PersonInfoConstant.updateSex);

		} else if (id == R.id.me_detail_brithday_layout) {
			if (is_from_talk) {
				return;
			}
			setBrithday();

		} else if (id == R.id.me_detail_my_email_layout) {
			if (is_from_talk) {
				return;
			}
			Intent intent4 = new Intent(MeDetailActivity.this,
					EditInfoActivity.class);
			intent4.putExtra("update_type", PersonInfoConstant.updateEmail);
			intent4.putExtra("oldStr", me_detail_my_email.getText().toString());
			startActivityForResult(intent4, PersonInfoConstant.updateEmail);

		} else if (id == R.id.me_detail_my_signature_layout) {
			if (is_from_talk) {
				return;
			}
			Intent intent5 = new Intent(MeDetailActivity.this,
					EditInfoActivity.class);
			intent5.putExtra("update_type", PersonInfoConstant.updateSignature);
			intent5.putExtra("oldStr", me_detail_my_signature.getText()
					.toString());
			startActivityForResult(intent5, PersonInfoConstant.updateSignature);

		} else {
		}
	}

	private void getPersonInfo() {
		loading.setVisibility(View.VISIBLE);
		GetPersonInfoInvokeItem item = new GetPersonInfoInvokeItem();
		HttpRequestAsyncTaskQueue
				.getInstance()
				.AddTask(
						new HttpTextAsyncTask(item)
								.SetRequestType(HttpRequestType.CACHE_FIRST_AND_SERVER),
						new OnHttpRequestTextListener() {

							@Override
							public void OnFail(boolean isCache, String reason) {
								Message msg = myHandler.obtainMessage();
								msg.what = 0;
								myHandler.sendMessage(msg);
							}

							@Override
							public void OnProgress(long total_bytes,
									long downloaded_bytes) {
							}

							@Override
							public void OnSuccess(HttpInvokeItem item,
									boolean isCache, String cacheFilePath) {
								Message msg = myHandler.obtainMessage();
								msg.what = 0;
								myHandler.sendMessage(msg);
								GetPersonInfoInvokeItem.GetPersonInfoInvokeItemResult result = ((GetPersonInfoInvokeItem) item)
										.getOutput();
								if (result != null
										&& result.status == HttpInvokeResultCode.RESULT_OK) {
									QYXUserEntity user = result.user;
									sex_type = user.sex;
									me_detail_my_avatar.SetUrl(APIConfiguration
											.getAvatarUrlNormal(user.custid,
													PacketType.PERSONAL));
									me_detail_my_name.setText(user.nickname);
									me_detail_my_area.setText(user.area);

									if (user.sex == 1) {
										me_detail_my_sex.setText(getResources()
												.getString(R.string.man));
									} else {
										me_detail_my_sex.setText(getResources()
												.getString(R.string.woman));
									}
									me_detail_my_email.setText(user.email);
									me_detail_my_app_num.setText(user.idenum);
									me_detail_age_tv.setText(user.age + "");
									me_detail_brithday_tv
											.setText(user.birthday);
									me_detail_my_signature
											.setText(user.signature);
								}
							}
						});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if (requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
			@SuppressWarnings("unchecked")
			ArrayList<PhotoItem> select_gl_arr = (ArrayList<PhotoItem>) data
					.getSerializableExtra("gl_arr");
			if (select_gl_arr.size() > 0) {
				for (int i = 0; i < select_gl_arr.size(); i++) {
					String path = select_gl_arr.get(i).getPath();
					Intent intent = new Intent(MeDetailActivity.this,
							ClipImageActivity.class);
					intent.putExtra("picPath", path);
					startActivityForResult(intent,
							CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE);
				}
			}

		} else if (requestCode == CHOOSE_TAKE_PHOTO_REQUEST_CODE) {
			String path = data.getStringExtra("big_pic_filename");
			Intent intent = new Intent(MeDetailActivity.this,
					ClipImageActivity.class);
			intent.putExtra("picPath", path);
			startActivityForResult(intent, CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE);
		} else if (requestCode == PersonInfoConstant.updateSex) {
			int sex = data.getIntExtra("sex", 0);
			sex_type = sex;
			if (me_detail_my_sex != null) {
				if (sex == 1) {
					me_detail_my_sex.setText(getResources().getString(
							R.string.man));
				} else if (sex == 0) {
					me_detail_my_sex.setText(getResources().getString(
							R.string.woman));
				}
			}
		} else if (requestCode == PersonInfoConstant.updateName) {
			if (me_detail_my_name != null)
				me_detail_my_name.setText(data.getStringExtra("result"));
		} else if (requestCode == PersonInfoConstant.updateEmail) {
			if (me_detail_my_email != null)
				me_detail_my_email.setText(data.getStringExtra("result"));
		} else if (requestCode == PersonInfoConstant.updateArea) {
			if (me_detail_my_area != null)
				me_detail_my_area.setText(data.getStringExtra("result"));
			updateInfo("area", data.getStringExtra("result"));
		} else if (requestCode == PersonInfoConstant.updateSignature) {
			if (me_detail_my_signature != null)
				me_detail_my_signature.setText(data.getStringExtra("result"));
		} else if (requestCode == PersonInfoConstant.updateAge) {
			if (me_detail_age_tv != null)
				me_detail_age_tv.setText(data.getStringExtra("result"));
		} else if (requestCode == CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE) {
			if (data == null) {
				return;
			}
			String pic_path = data.getStringExtra("pic_path");
			if (!TextUtils.isEmpty(pic_path)) {
				Bitmap photo = ImageUtil.CompressImageSameRadioScale(pic_path,
						100, 720, 720);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				photo.compress(Bitmap.CompressFormat.JPEG, 80, baos);

				byte[] bytes = baos.toByteArray();
				loading.setVisibility(View.VISIBLE);
				String url = APIConfiguration.getBaseUrl()
						+ "Cust/Cust/setCustAvatar?"
						+ APIConfiguration.getCustIdAndToken();
				uploadAvatar(bytes, url);
				if (photo != null && !photo.isRecycled()) {
					photo.recycle();
				}
			}
		}
	}

	private void updateAvatarDialog() {

		BottomDialog.showBottomDialog(MeDetailActivity.this, getResources()
						.getString(R.string.take_photo),
				getResources().getString(R.string.take_image), getResources()
						.getString(R.string.cancel), -1,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						takePhoto();
					}
				}, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						pickImage();
					}
				});

	}

	private void uploadAvatar(byte[] bytes, String url) {
		loading.setVisibility(View.VISIBLE);
		new UploadFile(bytes, new OnUploadFile2Listener() {

			@Override
			public void OnUploadFileSuccess(String response) {
				JSONObject json;
				try {
					json = new JSONObject(response);
					try {
						int status = json.optInt("status");
						String msg = json.optString("msg");
						IMApplication.showToast(msg);
						if (status == HttpInvokeResultCode.RESULT_OK) {
							// TODO
							String small = APIConfiguration.getAvatarUrlNormal(
									IMApplication.getCustId(),
									PacketType.PERSONAL);
							HttpStreamCache.getInstance().ClearCacheBitmap(
									small);
							HttpStreamCache.getInstance().ClearCacheBitmap(
									APIConfiguration.getAvatarUrlBig(
											IMApplication.getCustId(),
											PacketType.PERSONAL));
							me_detail_my_avatar.SetUrl(small, true);
						}

					} catch (Exception e) {
					}
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				String patern = APIConfiguration.getBaseUrl()
						+ "Cust/Cust/getCustQRCode?"
						+ APIConfiguration.getCustIdAndToken();
				HttpStreamCache.getInstance().ClearCacheBitmap(patern);
				myHandler.sendEmptyMessage(0);
			}

			@Override
			public void OnUploadFileFail(String response) {
				myHandler.sendEmptyMessage(0);
			}

		}, url);
	}

	private void takePhoto() {
		Intent getImageByCamera = new Intent(MeDetailActivity.this,
				TakePhotoActivity.class);
		ArrayList<ImageSize> size = new ArrayList<ImageSize>();
		size.add(new ImageSize(720, 720, ""));
		Bundle bundle = new Bundle();
		bundle.putSerializable("size", size);
		getImageByCamera.putExtras(bundle);
		startActivityForResult(getImageByCamera, CHOOSE_TAKE_PHOTO_REQUEST_CODE);
	}

	private void pickImage() {
		Intent getImage = new Intent(MeDetailActivity.this, PhotoActivity.class);
		getImage.putExtra("selected_count", 0);
		getImage.putExtra("max_select_count", 1);
		startActivityForResult(getImage, CHOOSE_IMAGE_REQUEST_CODE);
	}

	public Handler myHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 0) {
				if (loading != null) {
					loading.setVisibility(View.GONE);
				}
			}
			return false;
		}
	});

	private void setBrithday() {
		int selectedYear = -1;
		int selectedMonth = -1;
		int selectedDay = -1;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
				Locale.getDefault());
		try {
			if (!me_detail_brithday_tv.getText().toString()
					.equals("0000-00-00")) {
				Calendar calendar = Calendar.getInstance();
				String str = String.valueOf(sdf.parse(
						me_detail_brithday_tv.getText().toString()).getTime());
				calendar.setTimeInMillis(Long.valueOf(str));
				selectedYear = calendar.get(Calendar.YEAR);
				selectedMonth = calendar.get(Calendar.MONDAY);
				selectedDay = calendar.get(Calendar.DAY_OF_MONTH);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		MyDateDialog dateDialog = new MyDateDialog(selectedYear, selectedMonth,
				selectedDay,-1,-1, MeDetailActivity.this,false,true, new IDateDailogListener() {

					@Override
					public void OnDailogChick(String year, String Month,
							String Day, String hour, String minute) {
						updateInfo("birthday", year + "-" + Month + "-" + Day);
					}
				});
		dateDialog.showDialog();
	}

	private void updateInfo(String field, String value) {
		loading.setVisibility(View.VISIBLE);
		UpdatePersonInfoCommonHandle.udpatePersonInfo(field, value,
				new OnCommonCallBack() {

					@Override
					public void onSuccess(Object result) {
						myHandler.sendEmptyMessage(0);
						UpdateInfoInvokItem.UpdateInfoInvokItemResult results = (UpdateInfoInvokItem.UpdateInfoInvokItemResult) result;
						if (results != null
								&& results.status == HttpInvokeResultCode.RESULT_OK) {
							IMApplication.showToast(results.msg);
							getPersonInfo();
						}
					}

					@Override
					public void onFailed(String reason) {
						myHandler.sendEmptyMessage(0);
						IMApplication.showToast(reason);
					}
				});

	}

}
